﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ProtoBuf.Message;

namespace UI
{
    public class HeroReplacePage : Page
    {
        public UILabel title;
        public GameObject scrollView;
        public GameObject itemPrefab;
        public GameObject petItemPrefab;
        public SimpleGrid simpleGrid;
        public GameObject nextPageWordPref; //"点击显示下一页"
        
        public delegate void GoBattleCallback(int index);
        public GoBattleCallback m_callback;

        List<UIHero> heroList = new List<UIHero>();
        List<UIPet> petList = new List<UIPet>();
        int curShowedCount = 0;
        int positionIndex = 0;
        //string chosedGuid;
        float waitTime = 0;
        bool isHelp = false;//羁绊 助战

        string openPageType;

        IEnumerator UpdatePanel()
        {
            
            foreach (var item in simpleGrid.childs)
            {
                Destroy(item);
            }
            simpleGrid.childs.Clear();
            yield return new WaitForSeconds(waitTime);
            int count = 0;
            
            if(openPageType.Contains("hero"))
            {
                if (curShowedCount == 0)
                    heroList = StaticData.playerData.InstPlayerData.GetAvailableHerosForFormation(positionIndex);

                if (isHelp)
                {
                    var helpList = StaticData.playerData.InstPlayerData.GetHelpCamps();
                    var tempList = new List<UIHero>();
                    foreach (var ls in heroList)
                    {
                        foreach (var it in helpList)
                        {
                            var hero = StaticData.playerData.GetUIHero(it.Value.guid);

                            if (hero != null && hero.heroId == ls.heroId)
                            {
                                tempList.Add(ls);
                            }
                            else if (hero != null && hero.heroData.quality < (int)QualityValue.GREEN)
                            {
                                tempList.Add(ls);
                            }
                        }
                    }


                    var battleList = StaticData.playerData.InstPlayerData.BattleCamps;
                    foreach (var ls in heroList)
                    {
                        foreach (var it in battleList)
                        {
                            if (it.Value.hero != null && ls.heroId == it.Value.hero.heroId)
                            {
                                tempList.Add(ls);
                            }
                        }
                    }

                    foreach (var it in tempList)
                    {
                        heroList.Remove(it);
                    }


                }
                else
                {
                    //阵容上阵时，不能上和助阵中一样的人
                    var helpList = StaticData.playerData.InstPlayerData.GetHelpCamps();
                    var tempList = new List<UIHero>();
                    foreach (var ls in heroList)
                    {
                        foreach (var it in helpList)
                        {
                            var hero = StaticData.playerData.GetUIHero(it.Value.guid);

                            if (hero != null && hero.heroId == ls.heroId)
                            {
                                tempList.Add(ls);
                            }
                        }
                    }

                    foreach (var it in tempList)
                    {
                        heroList.Remove(it);
                    }
                }
                for (int i = curShowedCount; i < heroList.Count; i++)
                {
                    GameObject obj = Instantiate(itemPrefab);
                    simpleGrid.AddChild(obj);
                    obj.name = i.ToString();
                    obj.GetComponent<ChoseHeroItem>().SetHero(heroList[i].guid, false, isHelp);
                    obj.GetComponent<ChoseHeroItem>().goBattleBtn.AddComponent<UIDragScrollView>().scrollView = scrollView.GetComponent<UIScrollView>();


                    if (isHelp)
                    {
                        obj.GetComponent<ChoseHeroItem>().m_callback = this.OnHelpBattle;
                    }
                    else
                    {
                        obj.GetComponent<ChoseHeroItem>().m_callback = this.OnGoBattle;
                    }

                    count++;
                    if (count % 14 == 0)
                        yield return 1;
                    if (count % 160 == 0 && i + 1 < heroList.Count)
                    {
                        GameObject nextPageWordObj = Instantiate(nextPageWordPref);
                        nextPageWordObj.SetActive(true);
                        nextPageWordObj.GetComponent<NextPageWord>().m_callback = this.OnNextPage;
                        simpleGrid.AddChild(nextPageWordObj);
                        break;
                    }
                }
            }else if(openPageType.Contains("pet"))
            {
                petList = StaticData.playerData.InstPlayerData.GetAvailablePetsForFormation(positionIndex);
                
                for (int i = curShowedCount; i < petList.Count; i++)
                {
                    GameObject obj = Instantiate(petItemPrefab);
                    simpleGrid.AddChild(obj);
                    obj.name = i.ToString();
                    obj.GetComponent<ChosePetItem>().SetPet(petList[i].guid, false);
                    obj.GetComponent<ChosePetItem>().goBattleBtn.AddComponent<UIDragScrollView>().scrollView = scrollView.GetComponent<UIScrollView>();
                    obj.GetComponent<ChosePetItem>().m_callback = this.OnGoBattle;
                
                    count++;
                    if (count % 14 == 0)
                        yield return 1;
                    if (count % 160 == 0 && i + 1 < petList.Count)
                    {
                        GameObject nextPageWordObj = Instantiate(nextPageWordPref);
                        nextPageWordObj.SetActive(true);
                        nextPageWordObj.GetComponent<NextPageWord>().m_callback = this.OnNextPage;
                        simpleGrid.AddChild(nextPageWordObj);
                        break;
                    }
                }
            }
            curShowedCount += count;
            scrollView.GetComponent<UIScrollView>().ResetPosition();
        }

        void OnNextPage()
        {
            waitTime = 0.1f;
            StopCoroutine("UpdatePanel");
            StartCoroutine(UpdatePanel());
        }

        // 上阵
        void OnGoBattle(string guid)
        {
            
            //chosedGuid = guid;
            //未在阵型中的待替换角色
            if(openPageType.Contains("hero"))
            {
                UIHero hero = StaticData.playerData.GetUIHero(guid);

                CSFormationOn msg = new CSFormationOn();
                msg.guid = guid;
                msg.id = hero.heroId;
                msg.formatPos = positionIndex;//将被替换的角色位置，从1开始
                NetAPI.SendHttp(OpDefine.CSFormationOn, msg, OnGoBattleCallback);
            }else if(openPageType.Contains("pet"))
            {
                UIPet pet = StaticData.playerData.GetUIPet(guid);

                CSFormationOn msg = new CSFormationOn();
                msg.guid = guid;
                msg.id = pet.petId;
                msg.formatPos = positionIndex;//将被替换的角色位置，从1开始
                NetAPI.SendHttp(OpDefine.CSFormationOn, msg, OnGoBattleCallback);
            }

        }

        void OnHelpBattle(string guid)
        {
            CSHelperOn helper = new CSHelperOn();
            helper.guid = guid;
            helper.pos = positionIndex;
            NetAPI.SendHttp(OpDefine.CSHelperOn, helper, (obj,ok)=> 
            {
                if (ok)
                {
                    StaticData.playerData.InstPlayerData.ChangeHelpCamp(positionIndex,new UIHelpForamation(positionIndex,guid));
                    Close();
                }
            });
            
        }
        
        void OnGoBattleCallback(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                SCFormationOn msg = packet.kBody as SCFormationOn;
                UIHeroFormation formation = StaticData.playerData.InstPlayerData.GetBattleCamp(positionIndex);
                formation.InitData(msg.formationItem, true, true);
                StaticData.funcNavKit.OnFormationChange();
                if(openPageType.Contains("hero"))
                {
                    if (m_callback != null)
                    {
                       m_callback(positionIndex);
                    }
                }

            }
            Close();
        }

        protected override void DoOpen()
        {
            base.DoOpen();

            GetComponent<PageTweener>().Play();

            positionIndex = int.Parse(options["index"]);
            isHelp = options.ContainsKey("help");
            openPageType = options["openPageType"];

            waitTime = 0.5f;
            curShowedCount = 0;

            if (openPageType == "hero") {
                title.text = TableTextBlo.GetText("chose_gobattle_role");
            }
            else if (openPageType == "pet")
            {
                title.text = TableTextBlo.GetText("chose_gobattle_pet");
            }

            StopCoroutine("UpdatePanel");
            StartCoroutine(UpdatePanel());



        }
        protected override void DoClose()
        {
            foreach (var item in simpleGrid.childs)
            {
                Destroy(item);
            }
            simpleGrid.childs.Clear();

            base.DoClose();
        }
    }

}
